<template>
  <nut-config-provider :theme="theme" :theme-vars="themeVars">
    <view :style="{backgroundColor: themeVars.pageBackgroundColor,padding: themeVars.pagePadding,height: '100vh'}">
      <nut-searchbar v-model="queryParam.searchKey" @clear="clearSearch" @change="changeSearch"
                     placeholder="请输入产品、商家名称">
        <template #leftin>
          <Search2/>
        </template>
        <template #rightout>
          <nut-button @click="search" type="primary" size="small">搜索</nut-button>
        </template>
      </nut-searchbar>


      <view class="search-content" v-if="queryParam.searchType">
        <nut-tabs v-model="queryParam.searchType" align="left" :ellipsis="false" :title-gutter="10" @change="changeTab">
          <nut-tab-pane title="全部" pane-key="all"
                        :style="{padding: '10px' } ">
            <SearchAll v-if="data.length > 0" :name="agg.name" :number="agg.num" @clickTitle="clickTitle"
                       v-for="agg in data">
              <template v-if="agg.name=='商品'">
                <SpecCommodity @click="Taro.navigateTo({url:'/pages/view/commodityInfo/index?id='+product.id})"
                               :data="product" v-for="product in agg.list"/>
              </template>
              <template v-if="agg.name=='商家'">
                <item-shop  @click="Taro.navigateTo({url:'/pages/view/enterpriseIntro/index?id='+shop.id})" :data="shop"
                      v-for="shop in agg.list" style="margin-bottom: 5px"/>
              </template>
            </SearchAll>
            <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>

          </nut-tab-pane>
          <nut-tab-pane title="商品" pane-key="product"
                        :style="{padding: '10px'  } ">
            <SpecCommodity v-if="data.length > 0"
                           @click="Taro.navigateTo({url:'/pages/view/commodityInfo/index?id='+item.id})" :data="item"
                           v-for="item in data"/>

            <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>


          </nut-tab-pane>
          <nut-tab-pane title="商家" pane-key="enterprise"
                        :style="{padding: '10px'  } ">
            <item-shop    v-if="data.length > 0" :data="item"
                  @click="Taro.navigateTo({url:'/pages/view/enterpriseIntro/index?id='+item.id})" v-for="item in data"
                  style="margin-bottom: 5px"/>
            <nut-empty v-else :image="emptyUrl()" :image-size="100" description="暂无数据"/>

          </nut-tab-pane>

        </nut-tabs>

      </view>


      <view class="not-search-content" v-else>
        <SearchPanel title="热门搜索">
          <view>
            <nut-tag v-for="word in hotWords" class="single-line-text"
                     @click="clickHis(word)"
                     style="padding: 2px 5px;max-width:100px;background: rgba(250, 104, 93, 0.1);margin: 2px">
              <span style="color: rgba(250, 104, 93)">{{ word }}</span>
            </nut-tag>
          </view>
        </SearchPanel>
        <SearchPanel title="历史搜索">
          <view>
            <view @click="clickHis(hisSearch)" class="single-line-text"
                  style="width: 350px;font-size: 13px;color: #666666"
                  v-for="hisSearch in hisSearchList">
              {{ hisSearch }}
            </view>
          </view>
        </SearchPanel>
      </view>


    </view>

  </nut-config-provider>
</template>

<script>
import {ref} from 'vue';
import {IconFont} from '@nutui/icons-vue'
import {Search2, Left, Photograph, Message} from '@nutui/icons-vue-taro'
import useTheme from "../../../hooks/useTheme";
import SearchPanel from "../../../components/searchPanel/index.vue";
import Shop from "../../../components/shop/index.vue";
import SpecCommodity from "../../../components/specCommodity/index.vue";
import SearchAll from "../../../components/searchAll/index.vue";
import {commonSearch} from "../../../api/login";
import Taro from "@tarojs/taro";
import {twPublishMyPage} from "../../../api/publish";
import {twProductPageApi} from "../../../api/product";
import {twEnterprisePageApi} from "../../../api/enterprise";
import {searchHotWord} from "../../../api/dev";
import {emptyUrl} from "../../../utils/imgUtils";

const hotWords = ref([])
const data = ref([])
const {theme, themeVars} = useTheme()

const getHisSearchList = () => {
  return Taro.getStorageSync("hisSearchKey") ? JSON.parse(Taro.getStorageSync("hisSearchKey")) : [];
}


const hisSearchList = ref([]);
hisSearchList.value = getHisSearchList()


const queryParam = ref({current: 1, size: 10, pages: 0, searchType: "", searchKey: ''})
const getData = () => {
  queryParam.value.searchType = queryParam.value.searchType || 'all';
  if (queryParam.value.searchType == 'all' && queryParam.value.searchKey.trim()) {

    queryParam.value.size = 3;
    commonSearch({...queryParam.value, sortField: 'createTime', sortOrder: "descend"}).then(res => {
      if (200 == res.code) {
        data.value = res.data
        /*   data.value = [...data.value, ...res.data.records]
           queryParam.value.pages = res.data.pages;
           console.log("queryParam", queryParam.value)*/
        console.log("res.data", res.data)
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }


  if (queryParam.value.searchType == 'product' && queryParam.value.searchKey.trim()) {
    twProductPageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend"}).then(res => {
      if (200 == res.code) {
        data.value = [...data.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
        console.log("queryParam", queryParam.value)
        console.log("res.data", res.data)
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }


  if (queryParam.value.searchType == 'enterprise' && queryParam.value.searchKey.trim()) {
    twEnterprisePageApi({...queryParam.value, sortField: 'createTime', sortOrder: "descend",status:'ENABLE'}).then(res => {
      if (200 == res.code) {
        data.value = [...data.value, ...res.data.records]
        queryParam.value.pages = res.data.pages;
        console.log("queryParam", queryParam.value)
        console.log("res.data", res.data)
      }
    }).finally(() => {
      Taro.stopPullDownRefresh();
      loadMoreLoading.value = false

    })
  }


}


const refresh = () => {
  queryParam.value.current = 1;
  queryParam.value.size = 10;
  data.value = []
  getData()
}

const loadMoreLoading = ref(false);
const loadMore = () => {
  if (queryParam.value.current >= queryParam.value.pages) {
    console.log("没有更多数据了")
    Taro.showToast({title: "没有更多数据了", icon: 'none', duration: 1500,});
    return
  }
  loadMoreLoading.value = true
  queryParam.value.current = queryParam.value.current + 1
  getData()
}


const search = () => {
  const searchContent = queryParam.value.searchKey.trim();
  if (searchContent) {
    const hisArr = getHisSearchList();
    Taro.setStorageSync("hisSearchKey", JSON.stringify([searchContent, ...hisArr.slice(0, 10)]))
    hisSearchList.value = getHisSearchList()
    refresh()
    getHotSearchWord()
  } else {
    Taro.showToast({title: "请输入有效词", icon: 'none', duration: 1500,});
    data.value = []
  }

}

const changeTab = ({title, paneKey, disabled}) => {
  console.log("changeTab", title, paneKey, disabled)
  queryParam.value.searchType = paneKey
  refresh()
}

const clearSearch = () => {
  queryParam.value.searchType = ""

}

const changeSearch = (val) => {
  if (!val) {
    queryParam.value.searchType = ""
  }
}

const clickTitle = (name) => {
  console.log("clickTitle", name)
  if (name == "商品") {
    queryParam.value.searchType = "product"
    refresh()
  } else if (name == "商家") {
    queryParam.value.searchType = "enterprise"
    refresh()
  }

}

const clickHis = (hisWord) => {
  queryParam.value.searchKey = hisWord;
  refresh()
}

const getHotSearchWord = () => {
  searchHotWord().then(res => {
    console.log("searchHotWord", res)
    if (200 == res.code) {
      hotWords.value = (res.data || []).slice(0, 10)
    }
  })
}
getHotSearchWord()

export default {
  methods: {
    emptyUrl() {
      return emptyUrl
    }
  },
  components: {IconFont},

  // 可以使用所有的 Vue 生命周期方法
  mounted() {
  },

  onLoad() {
    // console.log(11)
    queryParam.value.searchType = ""

  },

  onReady() {
  },

  onShow() {
  },

  onHide() {
  },

  onPullDownRefresh() {
    console.log("onPullDownRefresh")
    refresh()
  },
  onReachBottom() {
    console.log("onReachBottom")
    loadMore()
  },


  setup() {


    return {
      theme,
      themeVars,

      Taro,
      queryParam,
      data,
      search,
      hisSearchList,
      changeTab,
      clearSearch,
      changeSearch,
      clickTitle,
      clickHis,
      hotWords

    }
  }

}

</script>

<style>


</style>